package com.zy.explore.report.application.service;

import com.zy.explore.report.infrastructure.util.FileUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * description OSS服务实现类
 *
 * @author ZY
 * @date 2021年05月15日 22:19
 */
@Slf4j
@Service
public class OssService {

    @Value("${alibaba.cloud.oss.endpoint:}")
    private String endpoint;

    @Value("${alibaba.cloud.oss.bucket:}")
    private String bucketName;

    @Resource
    private OSSClient ossClient;

    /**
     * 上传MultipartFile返回下载地址
     * @param file 上传的文件
     * @return 返回下载地址
     * @throws IOException IO异常
     */
    public String uploadFile(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        InputStream ins = file.getInputStream();
        assert filename != null;
        File f = new File(filename);
        FileUtil.inputStreamToFile(ins, f);
        // 上传文件流。
        InputStream inputStream = new FileInputStream(f);
        PutObjectResult result = ossClient.putObject(bucketName, filename, inputStream);
        log.info("OSSService uploadFile result = {}, etag = {}, requestid = {}", JSON.toJSONString(result), result.getETag(), result.getRequestId());
        // 删除文件
        f.delete();
        // 返回下载地址
        return "https://" + bucketName + "." + endpoint + "/" + URLEncoder.encode(filename, "UTF-8");
    }

    /**
     * 上传文件
     *
     * @param file        文件
     * @param objectName  对象名称
     * @param contentType 内容类型
     * @param fileName    文件名称
     * @return {@link String} 返回下载地址
     * @throws UnsupportedEncodingException 不支持的编码异常
     */
    public String uploadFile(byte[] file, String objectName, String contentType, String fileName) throws UnsupportedEncodingException {
        log.info("uploadFile log: bucketName = {}, objectName = {}, contentType = {}, fileName = {}", bucketName, objectName, contentType, fileName);
        ObjectMetadata meta = new ObjectMetadata();
        String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(file));
        if (fileName != null) {
            meta.setContentDisposition("attachment; filename=\"" + fileName + "\"");
        }
        meta.setContentMD5(md5);
        meta.setContentType(contentType);
        meta.setContentEncoding("utf-8");
        PutObjectResult result = ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(file), meta);
        log.info("OSSService uploadFile result = {}, etag = {}, requestid = {}", JSON.toJSONString(result), result.getETag(), result.getRequestId());
        // 返回下载地址
        return "https://" + bucketName + "." + endpoint + "/" + URLEncoder.encode(objectName, "UTF-8");
    }
}
